package com.tianpengtech.im.server.handler;


import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.Aio;
import org.tio.core.ChannelContext;

import com.tianpengtech.im.common.ImPacket;
import com.tianpengtech.im.common.ImSessionContext;
import com.tianpengtech.im.common.packets.Command;
import com.tianpengtech.im.common.packets.GroupResUsers;
import com.tianpengtech.im.common.packets.GroupResUsers.Builder;
import com.tianpengtech.im.common.packets.GroupUsersReqBody;
import com.tianpengtech.im.common.packets.UserOnline;
import com.tianpengtech.im.common.packets.Users;
import com.tianpengtech.web.partybulid.model.CUserExt;


public class HeartbeatReqHandler implements ImBsHandlerIntf
{
	
	private static Logger log = LoggerFactory.getLogger(HeartbeatReqHandler.class);

	@Override
	public Object handler(ImPacket packet, ChannelContext<ImSessionContext, ImPacket, Object> channelContext) throws Exception
	{
		log.info("来了一次心跳....");
		/**
		 * 服务器对应组的连接 
		 */
		
		if (packet.getBody() != null)
		{
			GroupUsersReqBody reqBody = GroupUsersReqBody.parseFrom(packet.getBody());
			/**查询前组的用户***/
			List<CUserExt> users =  CUserExt.dao
					.find("select * from c_user_ext t WHERE t.user_id in (select uid from im_member where mid = ? )", 
							Integer.parseInt(reqBody.getGroupid()));
			
			if (Aio.getChannelContextsByGroup(channelContext.getGroupContext(), reqBody.getGroupid()) != null) {
			Builder b = GroupResUsers.newBuilder().setTime(0l);
			/**遍历当前组的用户***/
			for(CUserExt _u : users){
				UserOnline userOnline = UserOnline.USER_ONLINE_ON;
				/***遍历在线的用户**/
				for (ChannelContext<ImSessionContext, ImPacket, Object> _channelContext : 
					Aio.getChannelContextsByGroup(channelContext.getGroupContext(), reqBody.getGroupid()).getObj()) {  
						/**判断用户是否在线***/
						if(_u.getUserId().toString().equals(_channelContext.getUserid())){
							userOnline = UserOnline.USER_ONLINE_OFF;
						}
				}
				Users us = Users.newBuilder().setUserid(_u.getUserId()).setName(_u.getRealname()).setIsOnline(userOnline).build();			
				b.addUsers(us);
			}
			GroupResUsers res = b.build();
			byte[] body = res.toByteArray();
			
			ImPacket respPacket = new ImPacket();
			respPacket.setCommand(Command.COMMAND_GROUP_USERS);
			respPacket.setBody(body);
			
			Aio.send(channelContext, respPacket);
			}
		}
		return null;
	}
}
